package io.renren.modules.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.common.entity.GoodsInfoEntity;
import io.renren.common.utils.*;
import io.renren.modules.pms.dto.OrderItemDTO;
import io.renren.modules.pms.entity.GoodsStockEntity;
import io.renren.modules.pms.entity.OrderItemEntity;
import io.renren.modules.pms.service.GoodsInfoService;
import io.renren.modules.pms.service.GoodsStockService;
import io.renren.modules.pms.service.OrderItemService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.renren.modules.pms.dao.OrderDao;
import io.renren.modules.pms.entity.OrderEntity;
import io.renren.modules.pms.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Resource
    private GoodsStockService goodsStockService;

    @Resource
    private GoodsInfoService goodsInfoService;

    @Resource
    private OrderItemService orderItemService;

    @Resource
    private OrderDao orderDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void generateOrder(OrderItemDTO[] orderItemDTO) {
        // 生成订单编号、计算订单总金额
        OrderEntity orderEntity = new OrderEntity();
        // 订单初始总金额
        BigDecimal totalPrice = new BigDecimal("0.00");

        // 此处默认使用UUID生成订单编号，可根据具体业务生成
        orderEntity.setOrderNo(UUID.randomUUID().toString());
        //orderEntity.setUserId(ShiroUtils.getUserId());
        //orderEntity.setUserType(1);
        orderEntity.setOrderStatus(1);
        orderEntity.setTotalPrice(totalPrice);
        orderEntity.setDeleteStatus(0);
        //orderEntity.setCreateBy(ShiroUtils.getUserEntity().getUsername());
        orderEntity.setCreateTime(new Date());
        // 先生成订单
        orderDao.insert(orderEntity);

        List<OrderItemEntity> orderItemList = new ArrayList<>(orderItemDTO.length);
        List<GoodsStockEntity> stockEntityList = new ArrayList<>(orderItemDTO.length);
        // 与订单关联的商品
        for (OrderItemDTO item : orderItemDTO) {
            OrderItemEntity orderItemEntity = new OrderItemEntity();
            GoodsStockEntity goodsStockEntity = new GoodsStockEntity();
            // 每项商品关联对应订单
            orderItemEntity.setOrderId(orderEntity.getOrderId());
            Integer goodsId = item.getGoodsId();
            orderItemEntity.setGoodsId(Long.valueOf(goodsId));
            Integer num = item.getNum();
            orderItemEntity.setQuantity(item.getNum());
            GoodsInfoEntity goodsInfo = goodsInfoService.query().eq("id", goodsId).one();
            // 订单总金额 = （商品数量 * 商品单价）+（...）
            totalPrice = totalPrice.add(goodsInfo.getPrice().multiply(new BigDecimal(num.toString())));
            orderItemEntity.setPrice(goodsInfo.getPrice());
            GoodsStockEntity stockEntity = goodsStockService.query().eq("goods_id", goodsId).one();
            goodsStockEntity.setId(stockEntity.getId());
            // 修改商品库存
            goodsStockEntity.setNum(stockEntity.getNum() - num);
            orderItemList.add(orderItemEntity);
            stockEntityList.add(goodsStockEntity);
        }
        UpdateWrapper<OrderEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id", orderEntity.getOrderId());
        updateWrapper.set("total_price", totalPrice);
        // 修改订单总金额
        orderDao.update(null, updateWrapper);

        // 添加订单项数据
        orderItemService.saveBatch(orderItemList);

        // 修改库存
        goodsStockService.updateBatchById(stockEntityList);
    }
}
